package com.bluedot.www.core.service;

import com.bluedot.www.core.pojo.DO.Algorithm;
import com.bluedot.www.core.utils.AlgorithmCutoverUtils;
import com.bluedot.www.core.utils.ImageUtil;
import com.bluedot.www.framework.mvc.servlet.http.MultipartFile;
import com.bluedot.www.framework.mvc.servlet.http.ResponseEntity;
import org.apache.commons.fileupload.FileUploadException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author GUOZHIPENG
 * @version 1.0
 * @date 2021/9/1 16:13
 */
public class AnalyzeService {
    public static Object execute(String methodName, Object[] param) throws IOException, FileUploadException {
        AnalyzeService analyzeService = new AnalyzeService();
        Object result = null;
        switch (methodName) {
            case "preHandle":
                result = analyzeService.preHandle((MultipartFile) param[0], (long) param[1]);
                break;
            default:
                throw new RuntimeException("Method NOT FOUND, method name: " + methodName);
        }
        return result;
    }

    /**
     * 图片预处理
     *
     * @param file  图片
     * @param preId 预处理算法id
     * @return java.util.List<com.bluedot.www.framework.mvc.servlet.http.MultipartFile>
     * @author GUOZHIPENG
     * @date 2021/9/1 16:26
     */
    private ResponseEntity preHandle(MultipartFile file, Long preId) throws IOException, FileUploadException {
        Algorithm pre = (Algorithm) AlgorithmService.execute("findAlgorithmById", new Object[]{preId});
        BufferedImage image = ImageUtil.multipartFileToBufferedImage(file);
        BufferedImage preImag;
        if (preId == null || pre == null) {

            preImag = AlgorithmCutoverUtils.defaultPreAlgorithm(image);

            //preImag=AlgorithmHandler.preHandleImage(image);
        } else {

            preImag = AlgorithmCutoverUtils.preAlgorithm(image, pre.getLocation());
        }
        try {
            //Thumbnails.of(preImag).scale(1).toFile("D://8new.png");
            //Thumbnails.of(preImag).scale(1).toFile("src/test/resources/img/8new.png");
            //ImageIO.write(preImag,"jpg",new File("D://pre.jpg"));
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(preImag, "jpg", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            return new ResponseEntity("pre" + file.getOriginalFilename(), input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
